package dao;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.naming.NoInitialContextException;

import form.ConnectionDB;

import model.Baomat;

public class BaomatDAO {
	public static Boolean insert(Baomat baomat, String email)
			throws ClassNotFoundException, SQLException {
		Connection connection = ConnectionDB.getConnection();
		String sql = "insert into baomat(Email_baove,email,CMND,Ngaycap,Noicap) values (?,?,?,?,?)";
		PreparedStatement ps = connection.prepareStatement(sql);
		ps.setString(1, baomat.getEmailbaove());
		ps.setString(2, email);
		ps.setString(3, baomat.getCmnd());
		ps.setDate(4, baomat.getNgaycap());
		ps.setString(5, baomat.getNoicap());
		int change = 0;
		change = ps.executeUpdate();
		if (change > 0) {
			return true;
		} else {

			return false;
		}
	}

	public static ArrayList<Baomat> select(String email)
			throws ClassNotFoundException, SQLException {
		Connection connection = ConnectionDB.getConnection();
		ArrayList<Baomat> listBaomat = new ArrayList<>();
		String sql = "select * from baomat where email =?";
		PreparedStatement ps = connection.prepareStatement(sql);
		ps.setString(1, email);
		ResultSet resultSet = ps.executeQuery();
		while (resultSet.next()) {
			String emailbaove = resultSet.getString("Email_baove");
			String cmnd = resultSet.getString("CMND");
			Date ngaycap = resultSet.getDate("Ngaycap");
			String noicap = resultSet.getString("Noicap");
			listBaomat.add(new Baomat(emailbaove, cmnd, ngaycap, noicap));
		}
		connection.close();
		return listBaomat;

	}

	public static ArrayList<Baomat> selectAll() throws ClassNotFoundException,
			SQLException {
		Connection connection = ConnectionDB.getConnection();
		ArrayList<Baomat> listBaomat = new ArrayList<>();
		String sql = "select * from baomat";
		PreparedStatement ps = connection.prepareStatement(sql);
		ResultSet resultSet = ps.executeQuery();
		while (resultSet.next()) {
			String emailbaove = resultSet.getString("Email_baove");
			String cmnd = resultSet.getString("CMND");
			Date ngaycap = resultSet.getDate("Ngaycap");
			String noicap = resultSet.getString("Noicap");
			listBaomat.add(new Baomat(emailbaove, cmnd, ngaycap, noicap));
		}
		connection.close();
		return listBaomat;

	}

	public static void main(String[] args) throws ClassNotFoundException,
			SQLException {
		ArrayList<Baomat> arraBaomat = BaomatDAO.selectAll();
		for (Baomat baomat : arraBaomat) {
			if (baomat.getEmailbaove().equalsIgnoreCase("dadada")) {
				System.out.println("Tồn tại");
			} else {
				
			}
		}
	}

}
